package com.simpleframe.security;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ActionContext;
import com.simpleframe.exception.SimpleValidtorException;
import com.simpleframe.util.Utils;
import com.simpleframe.validator.FieldsValidator;
import com.simpleframe.validator.ValidatorContext;
import com.simpleframe.validator.validators.EmailValidator;
import com.simpleframe.web.action.SimpleframeAction;
import com.sun.xml.internal.bind.v2.runtime.Name;


public abstract class AbstractLoginAction extends SimpleframeAction{
	
	protected String username;
	protected String password;
	protected String captcha;
	
//	public String execute() throws Exception {
//		System.out.println("登录初始化");
//		return INPUT;
//	}
	
	@Action("/login")
	public String login() throws Exception {
		
		//验证
		///fieldNotEmpty(username, "用户名不能为空");
		//fieldNotEmpty(password, "密码不能为空");
		
		//创建一个验证对象
		//往里面添加条件 
		//但是，如果一个字段为假时，不验证另一个对象内容，应怎样做？
		
		//if(hasMessage()){
		///	return INPUT;
		//}
		
//		loginValidator();
		
		try {
			User user = getUser();
			if(user==null || !user.getPassword().equals(password)){
				addError("用户名或密码错误");
				return INPUT;
			}
			System.out.println("---- 登录验证通过 ----");
			user.setRoleIds(getRoles(user.getId()));
			ActionContext.getContext().getSession().put(User.USER_SESSION, user);
			addMessage("你已成功登录");
		} catch (Exception e) {
			addError("登录系统出错，请连接管理员");
			e.printStackTrace();
			return INPUT;
		}
		
		return SUCCESS;
	}
	
	public void validateLogin(){
		System.out.println("==============="+username);
		
	}
	
	public void loginValidator(){
//		ValidatorContext vc = ValidatorContext.getContext();
//		vc.add(new EmailValidator(username));
//		vc.valida(this);
		if(Utils.isAllNull(username,password)){
			System.out.println("----登录初始化-----");
			throw new SimpleValidtorException();
		}
		
		FieldsValidator fv = new FieldsValidator(this);
		fv.notEmpty(username, "用户名不能为空");
		fv.notEmpty(password, "密码不能为空");
		fv.validator();
	}
	
	@Action("/logout")
	public String logout()throws Exception {
		ActionContext.getContext().getSession().remove(User.USER_SESSION);
		addMessage("你已经成功退出");
		return SUCCESS;
	}
	
	protected abstract User getUser()throws Exception;
	
	protected abstract List<Long> getRoles(Long id) throws Exception;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		System.out.println("set username");
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}
	
	
}
